package com.loan.market.util

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.loan.market.bean.Config
import com.loan.market.http.getHttpMap
import com.loan.market.http.request

fun Context.jump(url: String?, id: String? = null) {
    if (url.isNullOrEmpty()) return
    if (!id.isNullOrEmpty()) {
        afEvent("click_product_$id")
    }
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    startActivity(intent)
}

var config: Config? = null

fun AppCompatActivity.getConfig(block: (config: Config) -> Unit = {}) {
    if (config != null) {
        block(config!!)
        return
    }
    http {
        val map = getHttpMap(202)
        config = request<Config>(map)
        if (config != null) {
            block(config!!)
        }
    }
}

fun Fragment.getConfig(block: (config: Config) -> Unit = {}) {
    if (config != null) {
        block(config!!)
        return
    }
    http {
        val map = getHttpMap(202)
        config = request<Config>(map)
        if (config != null) {
            block(config!!)
        }
    }
}

fun Context.getAppVersion(): String? {
    return try {
        packageManager.getPackageInfo(packageName, 0).versionName
    } catch (e: Exception) {
        ""
    }
}

fun Activity.toPlay(pkg: String = packageName) {
    val play = "com.android.vending"
    try {
        val uri = Uri.parse("market://details?id=$pkg")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        intent.setPackage(play)
        startActivity(intent)
    } catch (e: Exception) {
    }
}